package com.example.esp32;


import android.view.MotionEvent;
import android.view.View;

/**
 * 这个工具可以使任何一个view进行拖动。
 */


public class DragViewUtil {
    public static void registerDragAction(View v,View vue) {
        v.setOnTouchListener(new TouchListener(vue));
//        registerDragAction(v,vue);
    }

//    /**
//     * 拖动View方法
//     *
//     * @param v     view
//     * @param delay 延迟
//     */
//    public static void registerDragAction(View v, long delay,View vue) {
//        v.setOnTouchListener(new TouchListener(delay));
//    }

    private static class TouchListener implements View.OnTouchListener {

        private float downX;
        private float downY;
        private long downTime;
        private long delay;
        private boolean isMove;
        private boolean canDrag;
        private  View vue;

//        private TouchListener() {
//            this(0);
//            this(1);
//        }

        private TouchListener(View vue){
            this.delay = 1;
            this.vue=vue;
        }

        private boolean haveDelay() {
            return delay > 0;
        }

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    downX = event.getX();
                    downY = event.getY();
                    isMove = false;
                    downTime = System.currentTimeMillis();
                    if (haveDelay()) {
                        canDrag = false;
                    } else {
                        canDrag = true;
                    }
                    break;
                case MotionEvent.ACTION_MOVE:
                    if (haveDelay() && !canDrag) {
                        long currMillis = System.currentTimeMillis();
                        if (currMillis - downTime >= delay) {
                            canDrag = true;
                        }
                    }
                    if (!canDrag) {
                        break;
                    }
                    final float xDistance = event.getX() - downX;
                    final float yDistance = event.getY() - downY;
                    if (xDistance != 0 && yDistance != 0) {
                        int l = (int) (vue.getLeft() + xDistance);
                        int r = (int) (l + vue.getWidth());
                        int t = (int) (vue.getTop() + yDistance);
                        int b = (int) (t + vue.getHeight());
//                        v.layout(l, t, r, b);
                        vue.setLeft(l);
                        vue.setTop(t);
                        vue.setRight(r);
                        vue.setBottom(b);
                        isMove = true;
                    }
                    break;
                default:
                    break;
            }
            return isMove;
        }

    }
}
